package 可重入锁.lock的不同方式.tryLock带参数;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class TryLock implements Runnable {
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        try {
            if (lock.tryLock(2, TimeUnit.SECONDS)) {
                System.out.println(Thread.currentThread().getName() + " 占据锁3S");
                Thread.sleep(3000);
            } else {
                System.out.println(Thread.currentThread().getName() + " 2S内得不到锁后，自动退出申请锁状态");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread())
                lock.unlock();
        }
    }
/*
    得到锁的用3s，另一个线程等2s得不到，该线程就自动退出
 */
    public static void main(String[] args) {
        TryLock lock = new TryLock();
        Thread thread1 = new Thread(lock,"第一个线程");
        Thread thread2 = new Thread(lock,"第二个线程");
        thread1.start();
        thread2.start();
    }
    //第二个线程 占据锁3S
    //第一个线程 2S内得不到锁后，自动退出申请锁状态
}
